<template>
  <div class="order ddingdan kuaishouyewu">
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-dark">
          <el-tabs v-model="cutTab" @tab-click="handleClick">
            <el-tab-pane
              label="视频业务"
              text-color="#fff"
              name="1"
              class="shipingyewu"
            >
            </el-tab-pane>
            <el-tab-pane label="直播业务" name="2"> </el-tab-pane>
          </el-tabs>
          <div class="xuanxiangkuang" v-if="this.isMobile">
            <el-select v-model="type" placeholder="请选择" @change="selectItem">
              <el-option
                v-for="item in tabNum == '1' ? voideList : streamingList"
                :key="item.bianhao"
                :label="item.bieming"
                :value="item.ziduan"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 内容部分 -->
    <div class="conter">
      <div class="dianzan" v-for="(item, index) in listData" :key="item.id">
        <div class="dianzanbiaoti">
          {{item.alias}} {{item.price}}{{item.unit_price}}
          <!-- {{item.icon}} -->
          <!-- <img :src="require('@/assets/' + item.tubiao)" />{{ item.bieming }} : -->
          <!-- {{ item.price + item.danwei }} -->
        </div>
        <!-- 头部字段 -->
        <div class="dianzanwenzi">
          <span v-for="(items, i) in item.order_explain" :key="i">{{ items }}</span>
        </div>
        <div class="xiadan">
          <div class="shipinlianjie">
              <!-- 表单部分 -->
            <el-form :model="item" :rules="rules" :ref="item.id">
              <!-- 链接部分 -->
              <el-form-item prop="url">
                <el-input
                  :placeholder="item.lianjieleixing | linkType"
                  clearable
                  v-model="item.url"
                ></el-input>
              </el-form-item>
              <el-form-item  v-if="item.need_text == false" prop="num">
                <!-- 订单数量 -->
                <el-input
                  :placeholder="
                    `请输入订单数量(最低下单数${item.min_cnt})${
                      item.gaoshuliang
                        ? ',(最高下单数' + item.max_cnt+ ')'
                        : ''
                    }`
                  "
                  clearable
                  oninput="value=value.replace(/[^\d]/g,'')"
                  v-model="item.num"
                  @focus="minmaxNum(item)"
                ></el-input>
              </el-form-item>
              <!-- 评论 -->
              <el-form-item prop="text" v-else class="business_comment">
                <div class="dianzanshuliang">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 3 }"
                    placeholder="请输入评论内容，每条空一行"
                    v-model="item.text"
                    @input="zhibojiandancifayanshijian"
                    @focus="minmaxText(item,index)"
                  >
                  </el-input>
                  <span class="video">已输入{{ item.textLength }}条</span>
                </div>
              </el-form-item>
              <el-form-item
                prop="time"
                v-if="item.need_time ===true"
                class="time"
              >
                <div class="xuanzeshijian">
                  <span>{{
                    item.need_interval === true
                      ? "请选择间隔时间"
                      : "请选择订单时间: "
                  }}</span>
                  <el-select
                    v-model="item.time"
                    placeholder="请选择订单时间"
                    style="width: 50%;margin-left: 6px;"
                  >
                    <el-option
                      v-for="items in hunherenqi"
                      :key="items.value"
                      :label="
                        `${items.value}${
                          item.unit_interval == '秒' ? '秒' : '小时'
                        }`
                      "
                      :value="items.value"
                    ></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <!-- <el-form-item>
                <div class="dianzanshuliang">
                <span class="video">评论内容</span><span class="video" style="margin-left: 50%;">已输入条</span>
                <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 3}" placeholder="请输入评论内容，每条空一行"></el-input>
                </div>
              </el-form-item> -->
            </el-form>
          </div>
          <!-- <div class="dianzanshuliang">
            <span class="video">下单数量</span>
            <el-input
              placeholder="请输入点赞数量(最低下单数100)"
              clearable
              autocomplete="off"
            ></el-input>
          </div> -->
          <div class="xuanzeshijian"></div>
          <div class="jine" style="margin-top:120px">
            <div class="audio">
              订单总价:
              <!-- 单价乘以数量 -->
              <span class="ztys" v-if="item.need_text==false &&item.need_time==false" >
                {{( item.price * item.num ).toFixed(2) | price}}
              </span>
                <!-- 单价乘以时间乘以数量 -->
              <span class="ztys" v-if=" item.need_text==false &&item.need_time==true">
                {{( item.price * item.num *item.time ).toFixed(2) | price}}
              </span>
              <!-- 单价乘以评论长度 -->
              <span class="ztys" v-if="item.need_text==true && item.need_time==false">
                {{ (item.price * item.textLength).toFixed(2) | price }}
              </span>
              <!-- 包时发言 -->
              <span class="ztys" v-if=" item.need_text==true &&item.need_time==true &&item.is_multiply==true  ">
                {{ (item.price * item.time).toFixed(2) | price }}
              </span>
            </div>
            <div class="audio">
              我的余额:
              <span class="ztys">
                {{ userBalance.balance }}
              </span>
            </div>
          </div>
          <div class="anniu">
            <el-button
              type="danger"
              round
              class="queding"
              @click="confirmOrder(item.id, index)"
              >确定</el-button>
          </div>
          <div class="tixing">
            下单默认接受以上条款，如介意请勿下单！
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { _debounce1 } from "@/public/App";
import { mapState } from "vuex";
export default {
  props: {},
  data() {
    var checkNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("下单数量不能为空"));
      }
      const reg = /^[0-9]+$/;
      if (!reg.test(value)) {
        callback(new Error("请输入数字！"));
      } else {
        if (this.max_cnt) {
          value > this.max_cnt
            ? callback(new Error(`下单数量不能超过${this.max_cnt}！`))
            : value;
        }
        if (value < this.min_cnt) {
          callback(new Error(`下单数量不能低于${this.min_cnt}！`));
        }else{
          callback();
        }
        // `if ((value*1)%(this.beishu*1)!=0){
        //   callback(new Error(`下单数量只能为${this.beishu}的倍数！`));
        // }else{
        //   callback();
        // }`
      }
    };
    var checkText = (rule, value, callback) => {
      if (!value) callback(new Error("评论数量不能为空"));
      if (this.max_cnt) {
        this.listData[this.textIndex].textLength > this.max_cnt
          ? callback(new Error(`评论数量不能超过${this.max_cnt}！`))
          :this.tabList[this.textIndex].textLength
      }
      if (this.listData[this.textIndex].textLength < this.min_cnt) {
          callback(new Error(`评论数量不能低于${this.min_cnt}！`));
      }else{
        callback();
      }
    };
    return {
      max_cnt:'',
      min_cnt:'',
      establish:'',             //测试
      cutTab:'1',
      listData:[],
      order_type:1,             //1抖音视频，2抖音直播，3快手视频，4快手直播
      page_index:1,
      page_cnt:10,
      tabNum: "1",
      type: "",
      voideList: [],
      streamingList: [],
      tabList: [],
      hunherenqi: [
        {
          value: "2"
        },
        {
          value: "3"
        },
        {
          value: "4"
        },
        {
          value: "5"
        },
        {
          value: "6"
        },
        {
          value: "8"
        },
        {
          value: "12"
        },
      ],
      rules: {
        url: [
          { required: true, message: "请输入链接！", trigger: "blur" },
          {
            pattern: /(http|https):\/\/([\w.]+\/?)\S*/,
            message: "未输入链接！"
          }
        ],
        num: [
          { required: true, message: "请输入下单数量！", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: '不允许输入非数字类型！' },
          { validator: checkNum, trigger: "blur" }
        ],
        time: [
          { required: true, message: "请选择订单时间！", trigger: "change" }
        ],
        text: [
          { required: true, message: "请输入评论内容！", trigger: "blur" },
          { validator: checkText, trigger: "blur" }
        ]
      },
      minNum: 0,
      maxNum: "",
      isMobile: false,
      textIndex: 0,
      beishu:1
    };
  },
  computed: {
    ...mapState(["userBalance"])
  },
  created() {
    this.DusinessList();
  },
  mounted() {
  },
  watch: {},
  methods: {
    //评论方法
    minmaxText(item,index){
      this.textIndex = index;
      this.min_cnt = item.min_cnt * 1;
      item.max_cnt
        ? (this.max_cnt = item.max_cnt * 1)
        : (this.max_cnt = "");
      this.textLength = 0;
      item.beishu
        ? this.beishu = item.beishu
        : this.beishu = 1
    },
    zhibojiandancifayanshijian(e) {
      let textarea = [];
      textarea = e.split("\n").filter(item => {
        return item != "";
      });
      this.listData[this.textIndex].textLength = textarea.length;
      this.listData[this.textIndex].text = e;
    },
    //输入最低和最高数量
    minmaxNum(item) {
      // console.log(item)
      // this.minNum = item.dishuliang * 1;
      this.min_cnt=item.min_cnt
      item.max_cnt
        ? (this.max_cnt = item.max_cnt * 1)
        : (this.max_cnt = "");
      this.textLength = 0;
      // item.beishu ? this.beishu = item.beishu: this.beishu = 1
    },
    // 确定触发
      confirmOrder(formname,i){
        this.$refs[formname][0].validate(valid=>{
          if(valid){
          let singleList=this.listData[i]
          let  amount=0
          let need_text=singleList.need_text
          let need_time=singleList.need_time
          let is_multiply=singleList.is_multiply
          //评论  单价
          if(need_text==true &&need_time==false){
             amount=singleList.textLength*singleList.price
          }
          //单价  数量
          if(need_text==false && need_time==false){
             amount = singleList.price * singleList.num
          }
          //单价  时间  数量
          if(need_text==false&& need_time==true){
              amount=singleList.price*singleList.time *singleList.num
          }
          //包时发言
          if(need_text==true&& need_time==true && is_multiply==true){
              amount=singleList.price*singleList.time
          }
          if(this.userBalance.balance< amount){
            this.$message({
              type:'error',
              message:'下单失败,你的余额不足'
            })
            return;
          }
          this.$confirm('请确认地址是否正确，正确地址格式应为：https://v.kuaishou.com/******，每次只能对一个地址下单，如果地址有误将导致失败，请认真核对！?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //走成功操作
          this.establishOrder(singleList,amount)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
          }
        })
      },
      //创建订单接口
  async establishOrder(singleList,amount){
        let data={
          priceCfgId:singleList.id,                             //商品ID
          url_site:singleList.url,                              //url链接
          buyCnt:singleList.num,                                //购买数量
          pay_money:amount ,                                    //应付金额
          time_duration:singleList.time,                        //持续时间
          comment_diy:singleList.text                           //评论内容
        }
        const [err, res] = await this.$http.request({
          url:'/createOrder',
          method:'post',
          data
        })
        if(err) return
        console.log(res)
        if(res.data.result===1){
          this.$message({
            type:'success',
            message:'下单成功'
          })
        }
      },
    //视频业务接口
    async DusinessList() {
      let data={
        order_type:this.order_type
      }
      const [err, res] = await this.$http.request({
        url: "/shopping",
        method: "GET",
        data
      });
      if (err) return;
      this.listData=res.data.data

      // const [err2, res2] = await this.$http.request({
      //   url: "yewujiage/",
      //   method: "POST"
      // });
      // if (err2) return;
      // this.voideList = res.data.shuiju.filter(item => {
      //   return item.leixing == "1";
      // });
      // this.streamingList = res.data.shuiju.filter(item => {
      //   return item.leixing == "2";
      // });
      // let priceArr = [];
      // for (let i in res2.data.jiage[0]) {
      //   if (i != "id" && i != "yonghu_id") {
      //     priceArr.push({
      //       name: i,
      //       price: res2.data.jiage[0][i].toFixed(2)
      //     });
      //   }
      // }
    //   priceArr.forEach(item => {
    //     this.voideList.forEach(item2 => {
    //       if (item.name == item2.ziduan) {
    //         item2.price = item.price;
    //       }
    //     });
    //     this.streamingList.forEach(item2 => {
    //       if (item.name == item2.ziduan) {
    //         item2.price = item.price;
    //       }
    //     });
    //   });
    //   this.voideList.forEach((item, i) => {
    //     item.time = 1;
    //     this.$set(this.voideList, item.num, 0);
    //     this.$set(this.voideList, item.url, "");
    //     this.$set(this.voideList, item.text, "");
    //     item.textLength = 0;
    //     item.yewushuoming = item.yewushuoming.split("。");
    //   });
    //   this.streamingList.forEach((item, i) => {
    //     this.$set(this.streamingList, item.num, 0);
    //     this.$set(this.streamingList, item.time, 1);
    //     this.$set(this.streamingList, item.url, "");
    //     this.$set(this.voideList, item.text, "");
    //     item.textLength = 0;
    //     item.yewushuoming = item.yewushuoming.split("。");
    //   });
    //   this.voideList = this.voideList.filter(item => {
    //     return item.zhuangtai === 1;
    //   });
    //   this.streamingList = this.streamingList.filter(item => {
    //     return item.zhuangtai === 1;
    //   });
    //   this.tabList = this.voideList;
    //   if (navigator.userAgent.match(/(iPhone|iPad|Android|ios)/i)) {
    //     this.type = this.voideList[0].ziduan;
    //     this.isMobile = true;
    //     this.tabList = this.tabList.filter(item => {
    //       return item.ziduan == this.type;
    //     });
    //   }

     },
     //tab栏切换
    handleClick: _debounce1(function(tab, e) {
      console.log(this.cutTab)
      if(this.cutTab==='1'){
        this.order_type=1
        this.DusinessList()
      }
      if(this.cutTab==='2'){
        this.order_type=2
        this.DusinessList()
      }
      switch (tab.index) {
        case "0":
          if (navigator.userAgent.match(/(iPhone|iPad|Android|ios)/i)) {
            this.type = this.voideList[0].ziduan;
            this.tabList = this.voideList.filter(item => {
              return item.ziduan == this.type;
            });
          } else {
            this.tabList = this.voideList;
          }
          break;
        case "1":
          if (navigator.userAgent.match(/(iPhone|iPad|Android|ios)/i)) {
            this.type = this.streamingList[0].ziduan;
            this.tabList = this.streamingList.filter(item => {
              return item.ziduan == this.type;
            });
          } else {
            this.tabList = this.streamingList;
          }
          break;
          return;
      }
    }),
    selectItem(val) {
      this.type = val;
      switch (this.tabNum) {
        case "1":
          this.tabList = this.voideList.filter(item => {
            return item.ziduan == this.type;
          });
          break;
        case "2":
          this.tabList = this.streamingList.filter(item => {
            return item.ziduan == this.type;
          });
      }
    }
  },
  filters: {
    linkType(val) {
      return val == "0"
        ? "请输入您的主页链接（分享复制到此）"
        : "请输入您的视频链接（分享复制到此）";
    },
    price(val) {
      return val == "NaN" ? (0).toFixed(2) : val;
    }
  }
};
</script>

<style scoped lang="stylus">
@import './Dbusiness.styl';
</style>
